package com.example.testnetty;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.testnetty.nettyserver.NettyServer;

import cn.jzvd.JZVideoPlayerStandard;
import io.netty.buffer.ByteBuf;

public class MainActivity extends AppCompatActivity implements NettyListener {


    private Button btn_send;//发送

    private NettyClient nettyClient;//socket操作连接对象

    private NettyClient nettyClientTwo;  //声磁长连接

    private JZVideoPlayerStandard videoplayer;

    private final String TAG = "MainActivity.class";

    public static Handler handler = null;

    private TextView tvText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        createHandler();

        intiView();
    }

    private void createHandler() {

        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                switch (msg.what){

                    case 0:

                        Bundle msgData = msg.getData();

                        String message = (String) msgData.get("data");

                        tvText.setText("返回信息"+ message);

                        break;

                    default:
                        break;
                }

            }
        };
    }

    private void intiView() {

//        initSocketTcp();//默认自动连接socket
//
//        initSocketTcpTwo();
//
//        videoplayer = findViewById(R.id.videoplayer);
//
//        videoplayer.setUp("http://app.kssbchina.com/videos_check/shashi/epo/shouhou/1555581166uPvH_13.mp4",
//                JZVideoPlayerStandard.SCREEN_WINDOW_NORMAL,
//                "");
////        jzvdStd.thumbImageView.setImageURI("http://p.qpic.cn/videoyun/0/2449_43b6f696980311e59ed467f22794e792_1/640");

        btn_send = findViewById(R.id.btn_send);

        tvText = findViewById(R.id.tv_text);

        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        NettyServer.initStart(Constans.TCP_PORT,getApplicationContext());

                    }
                }).start();


//                if (!nettyClient.getConnectStatus()) {//获取连接状态，必须连接才能点。
//                    Toast.makeText(MainActivity.this, "先连接", Toast.LENGTH_SHORT).show();
//                } else {
//                    JSONObject jsonObject = new JSONObject();//传个jsonobject给服务器
//                    long l = System.currentTimeMillis();
//                    try {
//                        jsonObject.put("msgType", "infomation");
//                        jsonObject.put("msgValue", "status");
//                        jsonObject.put("msgTime", l + "");
//
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }
//
//                    /*
//                    调用的发送。
//                     */
//                    nettyClient.sendMsgToServer(jsonObject.toString(), new ChannelFutureListener() {
//                        @Override
//                        public void operationComplete(ChannelFuture channelFuture) throws Exception {
//                            if (channelFuture.isSuccess()) {                //4
//                                Log.d(TAG, "Write auth successful");
//                            } else {
//                                Log.d(TAG, "Write auth error");
//                            }
//                        }
//                    });
//
//
//                }
            }

        });
    }


    @Override
    public void onBackPressed() {
        if (videoplayer.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        videoplayer.releaseAllVideos();
    }

    private void initSocketTcpTwo() {
        nettyClientTwo = new NettyClient(Constans.HOST, Constans.TCP_PORT);
        if (!nettyClientTwo.getConnectStatus()) {
            nettyClientTwo.setListener(MainActivity.this);
            nettyClientTwo.connect();
        } else {
            nettyClientTwo.disconnect();
        }

    }


    /*
      socket 端口号以及开始连接，配置接口监听
      */
    private void initSocketTcp() {
        nettyClient = new NettyClient(Constans.HOST, Constans.TCP_PORT);
        if (!nettyClient.getConnectStatus()) {
            nettyClient.setListener(MainActivity.this);
            nettyClient.connect();
        } else {
            nettyClient.disconnect();
        }
    }


    /*
     回调客户端接收的信息  解析 数据流， 转换为string
     */
    @Override
    public void onMessageResponse(final Object msg) {
        ByteBuf result = (ByteBuf) msg;
        byte[] result1 = new byte[result.readableBytes()];
        result.readBytes(result1);
        result.release();
        final String ss = new String(result1);

        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                Toast.makeText(MainActivity.this, "接收成功" + ss, Toast.LENGTH_SHORT).show();

                Log.e(TAG, ss);
            }
        });
    }


    //连接状态变化的时候 会走这
    @Override
    public void onServiceStatusConnectChanged(final int statusCode) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (statusCode == NettyListener.STATUS_CONNECT_SUCCESS) {
                    Log.e(TAG, "STATUS_CONNECT_SUCCESS:");
                    if (nettyClient.getConnectStatus()) {
                        Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_SHORT).show();
                    }

                    if (nettyClientTwo.getConnectStatus()) {
                        Toast.makeText(MainActivity.this, "声磁连接成功", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Log.e(TAG, "onServiceStatusConnectChanged:" + statusCode);
                    if (!nettyClient.getConnectStatus()) {
                        Toast.makeText(MainActivity.this, "网路不好，正在重连", Toast.LENGTH_SHORT).show();
                    }

                    if (!nettyClientTwo.getConnectStatus()) {
                        Toast.makeText(MainActivity.this, "声磁网路不好，正在重连", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }

}
